package com.lagou.edu.interceptor;

import com.lagou.edu.annotation.MySecurity;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Security拦截器
 *
 * @author Sinu
 * @Date 2021/6/27
 */
public class SecurityIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(MySecurity.class)) {
            //包含权限注解
            MySecurity annotation = method.getAnnotation(MySecurity.class);
            String[] names = annotation.value();
            if (names.length > 0) {
                //有配置
                String requestName = request.getParameter("username");
                for (String annotaName : names) {
                    if (annotaName.equals(requestName)) {
                        return true;
                    }
                }

                // 没有一个 匹配上
                response.sendRedirect("/noPermission.jsp");
                return false;
            } else {
                // 无配置 都可以访问
                return true;
            }
        }

        return true;
    }
}
